package com.tang.h2_demo.global.response;


import com.tang.h2_demo.global.Result;
import com.tang.h2_demo.global.ResultBuilder;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

public class GlobalReturnValueHandlerWrapper implements HandlerMethodReturnValueHandler {
    private HandlerMethodReturnValueHandler handler;

    public GlobalReturnValueHandlerWrapper(HandlerMethodReturnValueHandler handler) {
        this.handler = handler;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return handler.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        if (returnValue instanceof Void) {
            returnValue = ResultBuilder.DEFAULT_RESULT;
        } else {
            if (!(returnValue instanceof Result)) {
                returnValue = ResultBuilder.builderDefaultSuccess(returnValue);
            }
        }
        handler.handleReturnValue(returnValue,
                returnType,
                mavContainer,
                webRequest);
    }
}
